package com.panopset.game.blackjack;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

public class CountingSystems {

    public static String DFT_COUNTING_SYSTEM_KEY = "Hi-Lo";
    private static final int NAME_POS = 30;
    private final Map<String, CountingSystem> css

    = new HashMap<String, CountingSystem>();

    public CountingSystems(final List<String> systemsData) {
        int index = 0;
        for (String s : systemsData) {
            // Counting system defs will be > 31 in length.
            if (s.length() <= (NAME_POS + 1)) {
                continue;
            }
            // Ignore comments.
            if (s.indexOf("#") == 0) {
                continue;
            }
            // Ignore the title line.
            if (s.indexOf(" 2  3  4  5  6  7  8  9  T  A") == 0) {
                continue;
            }
            // We have a legitimate counting system definition.
            String key = s.substring(NAME_POS).trim();
            String dta = s.substring(0, NAME_POS);
            css.put(key, new CountingSystem(key, dta, index++));
        }
    }

    public int findSelectionNbr(final String key) {
        for (Entry<String, CountingSystem> e : css.entrySet()) {
            if (e.getValue().getName().equals(key)) {
                return e.getValue().getSelection();
            }
        }
        throw new ArrayIndexOutOfBoundsException(key);
    }

    public String findSelectionKey(final int selection) {
        for (Entry<String, CountingSystem> e : css.entrySet()) {
            if (e.getValue().getSelection() == selection) {
                return e.getValue().getName();
            }
        }
        throw new ArrayIndexOutOfBoundsException(selection);
    }

    private String[] keys;

    public String[] getKeys() {
        if (keys == null) {
            Set<CountingSystem> s = Collections
                    .synchronizedSortedSet(new TreeSet<CountingSystem>());
            for (Entry<String, CountingSystem> e : css.entrySet()) {
                s.add(e.getValue());
            }
            keys = new String[s.size()];
            int i = 0;
            for (CountingSystem cs : s) {
                keys[i++] = cs.getName();
            }
        }
        return keys;
    }

    private CountingSystem selected;
    public CountingSystem getSelected() {
        if (selected == null) {
            selected = css.get(DFT_COUNTING_SYSTEM_KEY);
        }
        return selected;
    }

    public void setCountingSystem(int position) {
        selected = css.get(findSelectionKey(position));
    }

    public void setDefault() {
        selected = css.get(DFT_COUNTING_SYSTEM_KEY);
    }

}
